package com.sdruixinggroup.mondayb2b.ui.fragments;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.google.gson.reflect.TypeToken;
import com.sdruixinggroup.mondayb2b.API.API;
import com.sdruixinggroup.mondayb2b.API.Constants;
import com.sdruixinggroup.mondayb2b.B2bApplication;
import com.sdruixinggroup.mondayb2b.R;
import com.sdruixinggroup.mondayb2b.interfaces.ObjectCallBack;
import com.sdruixinggroup.mondayb2b.models.UserInfor;
import com.sdruixinggroup.mondayb2b.ui.Activities.BindPhoneActivity;
import com.sdruixinggroup.mondayb2b.ui.Activities.RegisterActivity;
import com.sdruixinggroup.mondayb2b.ui.MainActivity;
import com.sdruixinggroup.mondayb2b.utils.UserInfoUtil;
import com.tencent.connect.UserInfo;
import com.tencent.connect.auth.QQToken;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import com.zhy.http.okhttp.OkHttpUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

import static com.sdruixinggroup.mondayb2b.API.Constants.QQ_APP_ID;
import static com.sdruixinggroup.mondayb2b.ui.fragments.ShoppingCartFragment.REFLUSH_COUNT;

/**
 * Created by 00029935 on 2017/11/17.
 */

public class LoginFragment extends BaseFragment {
    @BindView(R.id.iv_finish)
    ImageView ivFinish;
    @BindView(R.id.et_account)
    EditText etAccount;
    @BindView(R.id.et_psw)
    EditText etPsw;
    @BindView(R.id.tv_login)
    TextView tvLogin;
    @BindView(R.id.tv_register)
    TextView tvRegister;
    @BindView(R.id.tv_forget_psd)
    TextView tvForgetPsd;
    @BindView(R.id.tv_wx_login)
    TextView tvWxLogin;
    @BindView(R.id.tv_qq_login)
    TextView tvQqLogin;
    @BindView(R.id.progress)
    ProgressBar progress;
    // IWXAPI 是第三方app和微信通信的openapi接口
    private IWXAPI api;
    private Tencent mTencent;
    private Boolean fromH5 = false;

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(Object resp) {/* Do something */
        if (resp instanceof UserInfor.AuthorizationBean) {
            getActivity().finish();
        }

    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 通过WXAPIFactory工厂，获取IWXAPI的实例
        api = B2bApplication.getApi();
        //oauth = DiffDevOAuthFactory.getDiffDevOAuth();
        api.registerApp(Constants.APP_ID);
        EventBus.getDefault().register(this);
        fromH5 = getActivity().getIntent().getBooleanExtra("fromH5",false);
    }

    @Override
    protected int getInflateLayout() {
        return R.layout.login_fragment;
    }

    @Override
    protected void setUpView(View view) {
        if (UserInfoUtil.getIsLogin(getContext())) {

            Intent inten = new Intent(getContext(), MainActivity.class);
            startActivity(inten);
            getActivity().finish();
        }
         mTencent = Tencent.createInstance(QQ_APP_ID, getContext());
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        ButterKnife.bind(this, rootView);
        return rootView;
    }

    @OnClick({R.id.iv_finish, R.id.tv_login, R.id.tv_register, R.id.tv_forget_psd, R.id.tv_wx_login, R.id.tv_qq_login})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_finish:
                getActivity().finish();
                break;
            case R.id.tv_login:
                login();
                break;
            case R.id.tv_register:
                Intent intent = new Intent(getContext(), RegisterActivity.class);
                startActivity(intent);
                break;
            case R.id.tv_forget_psd:
                Intent it = new Intent(getContext(), RegisterActivity.class);
                it.putExtra("isForgetPSWD", true);
                startActivity(it);
                break;
            case R.id.tv_wx_login:
                if (!api.isWXAppInstalled()) {
                    showMsgToast("您还未安装微信客户端");
                    return;
                }
                // Intent intent1 = new Intent(getContext(), BindPhoneActivity.class);
                //  startActivity(intent1);
                final SendAuth.Req req = new SendAuth.Req();
                req.scope = "snsapi_userinfo";
                req.state = "none";
                Boolean b = api.sendReq(req);
                break;
            case R.id.tv_qq_login:
                Intent intent2 = new Intent(getContext(), BindPhoneActivity.class);
                // startActivity(intent2);
                mTencent.login(getActivity(), "all", new BaseUiListener());
                break;
        }
    }


    private void login() {
        String phone = etAccount.getText().toString().trim();
        if (TextUtils.isEmpty(phone)) {
            showMsgToast("请输入账号");
            return;
        }


        String pswd = etPsw.getText().toString().trim();
        if (TextUtils.isEmpty(pswd)) {
            showMsgToast("请输入密码");
            return;
        }
        progress.setVisibility(View.VISIBLE);
        String url = API.REGISTER_LOGIN + phone + "&password=" + pswd;
        HashMap<String, String> headers = new HashMap<>();
        headers.put("Accept", "*/*");

        TypeToken<UserInfor> typeToken = new TypeToken<UserInfor>() {
        };
        OkHttpUtils.post().url(url).headers(headers).build().execute(new ObjectCallBack<UserInfor>(typeToken) {
            @Override
            public void onError(Call call, Exception e, int id) {

                if (null != progress) {
                    progress.setVisibility(View.GONE);
                }
            }

            @Override
            public void onResponse(UserInfor response, int id) {
                if (null != response) {
                    if (response.getErr_code() == 0) {
                        showMsgToast("登录成功");
                        UserInfoUtil.saveToken(getActivity(), response.getAuthorization().getAccess_token());
                        UserInfoUtil.saveReflushToken(getActivity(), response.getAuthorization().getRefresh_token());
                       // Intent inten = new Intent(getContext(), MainActivity.class);
                       // startActivity(inten);
                        if(!fromH5){
                            EventBus.getDefault().post(123);
                            EventBus.getDefault().post(REFLUSH_COUNT);
                        }

                        getActivity().finish();
                    } else {
                        showMsgToast(response.getErr_msg());
                    }
                }

                if (null != progress) {
                    progress.setVisibility(View.GONE);
                }
            }
        });
    }

    private class BaseUiListener implements IUiListener {


//这个类需要实现三个方法 onComplete（）：登录成功需要做的操作写在这里
// onError onCancel 方法具体内容自己搜索

        public void onComplete(Object response) {
            // TODO Auto-generated method stub
            Log.e("HQQ", "response:: "+response.toString());
          //  showMsgToast("登录成功");
            try {
                //获得的数据是JSON格式的，获得你想获得的内容
                //如果你不知道你能获得什么，看一下下面的LOG
                Log.v("----TAG--", "-------------" + response.toString());
             String   openidString = ((JSONObject) response).getString("openid");
                mTencent.setOpenId(openidString);
                mTencent.setAccessToken(((JSONObject) response).getString("access_token"), ((JSONObject) response).getString("expires_in"));


                Log.v("TAG", "-------------" + openidString);
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                Log.e("HQQ", "-------------" + e);
            }
          /*  *//**到此已经获得OpneID以及其他你想获得的内容了
             QQ登录成功了，我们还想获取一些QQ的基本信息，比如昵称，头像什么的，这个时候怎么办？
             sdk给我们提供了一个类UserInfo，这个类中封装了QQ用户的一些信息，我么可以通过这个类拿到这些信息
             如何得到这个UserInfo类呢？获取详细信息的UserInfo ，返回的信息参看下面地址：
             http://wiki.open.qq.com/wiki/%E8%8E%B7%E5%8F%96%E7%94%A8%E6%88%B7%E4%BF%A1%E6%81%AF#1._Tencent.E7.B1.BB.E7.9A.84request.E6.88.96requestAsync.E6.8E.A5.E5.8F.A3.E7.AE.80.E4.BB.8B  */
            QQToken qqToken = mTencent.getQQToken();
            UserInfo info = new UserInfo(getContext().getApplicationContext(), qqToken);
            info.getUserInfo(new IUiListener() {
                @Override
                public void onComplete(Object o) {
                    //用户信息获取到了
                    try {
                        Log.e("HQQ"," o : "+o);
                        Log.v("用户名", ((JSONObject) o).getString("nickname"));
                        Log.v("用户姓名", ((JSONObject) o).getString("gender"));
                        Log.v("UserInfo",o.toString());
                       // Intent intent1 = new Intent(LoginActivity.this,MainActivity.class);
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }

                @Override
                public void onError(UiError uiError) {
                    Log.v("UserInfo","onError");
                }

                @Override
                public void onCancel() {
                    Log.v("UserInfo","onCancel");
                }
            });
        }

        @Override
        public void onError(UiError uiError) {
                    Log.e("HQQ"," uiError : "+uiError.errorDetail);
        }

        @Override
        public void onCancel() {
            Log.e("HQQ"," onCancel : ");
        }
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        mTencent.handleLoginData(data, new BaseUiListener());
        super.onActivityResult(requestCode, resultCode, data);

    }

}
